package com.googlecode.linkmein.domain;

import com.google.gdata.data.spreadsheet.ListEntry;
import com.google.gdata.data.spreadsheet.CustomElementCollection;
import static com.googlecode.linkmein.utils.Util.defaultString;

import java.util.List;
import java.util.ArrayList;
import java.util.Iterator;
import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class Resources implements Iterable<Resource> {
    private List<Resource> humanResources = new ArrayList<Resource>();


    public Resources(List<ListEntry> entries) {
        File file = new File("a.resource.log");
        ArrayList<String> strings = new ArrayList<String>();
        for (ListEntry entry : entries) {
            CustomElementCollection elements = entry.getCustomElements();
            List<String> tags = new ArrayList(elements.getTags());

            String englishName = defaultString(elements.getValue(tags.get(0)));
            String chineseName = defaultString(elements.getValue(tags.get(1)));
            String role = defaultString(elements.getValue(tags.get(2)));
            String projectName = defaultString(elements.getValue(tags.get(3)));
            humanResources.add(new Resource(new Name(englishName, chineseName), role, new Project(projectName)));
        }

        try {
            FileUtils.writeLines(file, strings, "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public Resources(Resource... resources) {
        for (Resource resource : resources) {
            humanResources.add(resource);
        }
    }

    public String toString() {
        return humanResources.toString();
    }

    public Iterator<Resource> iterator() {
        return humanResources.iterator();
    }

    public Resource findResource(Contact contact) {
        for (Resource humanResource : humanResources) {
            if (humanResource.isSameOne(contact)) {
                return humanResource;
            }
        }
        return Resource.NULL;
    }
}
